var express = require('express');
var router = express.Router();
const ListModel = require("../../models/ListModel")
const moment = require("moment")
const jwt = require('jsonwebtoken')
const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware')
/* GET home page. */
router.get('/',checkTokenMiddleware, function (req, res, next) {
  console.log(req.user)
  ListModel.find().sort({ time: -1 }).then(data => {
    res.json({
      code: '0',
      msg: '查找成功',
      data: data
    })
  }).catch(error => {
    res.json({
      code: '1000',
      msg: "查找失败",
      data: null
    })
  })

});

router.post('/',checkTokenMiddleware, function (req, res, next) {
  //表单验证
  if (!req.body.title) {
    res.json({
      code: "1001",
      msg: "title为空",
      data: null
    })
    return
  } else if (!req.body.account) {
    res.json({
      code: "1002",
      msg: "account为空",
      data: null
    })
    return
  }
  ListModel.create({ ...req.body, time: new Date(req.body.time) })
    .then(data => {
      res.json({
        code: '0',
        msg: '新增成功',
        data: data
      })
    })
    .catch(error => {
      console.log(error)
      res.json({
        code: '500',
        msg: '服务器错误',
        data: null
      })
    })
})

router.delete('/:id',checkTokenMiddleware, function (req, res, next) {
  //没有id都匹配不到这个

  ListModel.deleteOne({ _id: req.params.id }).then(data => {
    res.json({
      code: '0',
      msg: '删除成功',
      data: data
    })
  }).catch(error => {
    res.json({
      code: '1004',
      msg: '删除失败',
      data: null
    })
  })


})

router.get('/:id',checkTokenMiddleware, function (req, res, next) {
  ListModel.findById({ _id: req.params.id })
    .then(data => {
      res.json({
        code: '0',
        msg: '查找成功',
        data: data
      })
    })
    .catch(error => {
      res.json({
        code: '1005',
        msg: '查询错误',
        data: null
      })
    })
})

router.patch('/:id',checkTokenMiddleware, function (req, res, next) {
  ListModel.updateOne({ _id: req.params.id }, req.body)
    .then(data => {
      ListModel.findById({ _id: req.params.id })
        .then(data => {
          res.json({
            code: "0",
            msg: '更新成功',
            data: data
          })
        })
        .catch(error => {
          res.json({
            code: "1007",
            msg: '查找失败',
            data: null
          })
        })
    })
    .catch(error => {
      res.json({
        code: "1006",
        msg: '更新失败',
        data: null
      })
    })
})
module.exports = router;
